/* 
 * Copyright (C), 2016-2020, 厦门盈欣宝金融信息服务有限公司
 * Project Name :boot-parent
 * File Name: org.easytouesit.mongodb.dao
 * Encoding UTF-8 
 * Version: 1.0 
 * Date: 2018-08-27 14:51
 * History:  
 * 1. Date: 2018-08-27
 *    Author: guojm 
 *    Modification: 新建
 * 2. ...
 */
package org.easytouesit.mongodb.dao;

import org.easytouesit.mongodb.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author guojm
 * @version V1.0
 * @date 2018-08-27 下午 14:51
 */
@Repository("userDao")
public class UserDaoImpl implements UserDao {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public List<User> findAll() {
        return mongoTemplate.findAll(User.class);
    }

    @Override
    public User getUser(Integer id) {
        return mongoTemplate.findOne(new Query(Criteria.where("id").is(id)),User.class);
    }

    @Override
    public void update(User user) {
        Query query = new Query(Criteria.where("id").is(user.getId()));
        Update update = Update.update("name",user.getName()).set("age",user.getAge());
        mongoTemplate.updateMulti(query,update,User.class);
    }

    @Override
    public void insert(User user) {
        mongoTemplate.insert(user);
    }

    @Override
    public void insertAll(List<User> users) {
        mongoTemplate.insertAll(users);
    }

    @Override
    public void remove(Integer id) {
        mongoTemplate.remove(new Query(Criteria.where("id").is(id)),User.class);
    }

    @Override
    public List<User> findByPage(User user, Pageable pageable) {

        Query query= new Query();
        if(user !=null && user.getName() != null){
            query = new Query(Criteria.where("name").regex("^"+user.getName()));
        }
        List<User> list = mongoTemplate.find(query.with(pageable),User.class);
        return list;
    }
}
